TITLE quickSort
INCLUDE Irvine32.inc
.data
arr DWORD 1d,10d,4d,3d,0d,9d,6d,8d,7d,5d,2d;,1h,9h,0h,4h,5h
i	DWORD ?
j	DWORD ?
x	DWORD ?
temp DWORD ?
w	DWORD ?
address DWORD ?
space BYTE " ",0
n	DWORD 10d
.code

writeArry PROC
push	ebp
mov	ebp,esp
push	eax
push	edx
push	esi

mov		esi,address
mov		eax,0
mov		edx,offset space
writeFor:
cmp		eax,n
jg		endWrite
push	eax
mov		eax,[esi+4*eax]
call	writeDec
call 	writeString
pop		eax
add		eax,1
jmp		writeFor
endWrite:
call	crlf

pop		esi
pop		edx
pop		eax
mov		esp,ebp
pop		ebp
ret
writeArry ENDP



split PROC
push ebp			;save old base pointer value
mov ebp,esp			;set the new base pointer value

push	eax
push	ebx
push	ecx
push	edi
push	esi





mov eax,[ebp+8]		;eax array a
mov ebx,[ebp+12]	;ebx low
mov	ecx,[ebp+16]	;exc high

mov  i,ebx		;i = low
mov	 edi,[eax+4*ebx]; x =a[low]
mov	 x,edi
mov  j,ebx	;
add  j,1		;j=low+1
splitFor:
	cmp j,ecx	;if j>high
	JG	outFor			 
	;if
		mov edi,j
		mov esi,[eax+4*edi]
		cmp	esi,x	;if a[j]>x
		JG	outerIfEnd
		add i,1	;i++
		iIf:
			cmp	i,edx	;i!=j
			je	innerIfEnd
			
			mov esi,i
			mov	esi,[eax+4*esi]
			mov temp,esi		;temp=a[i]
			mov esi,[eax+4*edi]	;esi=a[j]
			push edi
			mov	edi,i
			mov [eax+4*edi],esi	;a[i]=a[j]
			pop	edi
			mov esi,temp
			mov [eax+4*edi],esi	;a[j]=temp
		innerIfEnd:
	outerIfEnd:
	add	j,1
	jmp	splitFor
outFor:
mov esi,i
mov esi,[eax+4*esi]	;esi=a[i]
mov [eax+4*ebx],esi	;a[low]=a[i]
mov esi,i
mov edi,x
mov [eax+4*esi],edi


pop		esi
pop		edi
pop		ecx
pop		ebx
pop		eax
mov		esp,ebp
pop		ebp
ret
split ENDP



;quickSort
quickSort PROC

push ebp			;save old base pointer value
mov ebp,esp			;set the new base pointer value
push	eax
push	ebx
push	ecx
push	edi
push	esi
push	w

mov eax,[ebp+8]		;eax array a
mov ebx,[ebp+12]	;ebx low
mov	ecx,[ebp+16]	;exc high
cmp ebx,ecx			;low>=high
jge over
;call split
push	ecx
push	ebx
push	eax
call	split
add esp,12

;call	writeArry


mov edi,i


mov w,edi ;w=split(a,low,high)
sub w,1	;w=w-1
push	w
push	ebx
push	eax
call	quickSort
add	esp,12

add w,2		;w=w+2
push	ecx
push	w
push	eax
call	quickSort
add	esp,12

over:
pop		w
pop		esi
pop		edi
pop		ecx
pop		ebx
pop		eax

mov esp, ebp ; Deallocate local variables
pop ebp ; Restore the caller's base pointer value


ret
quickSort ENDP


main PROC
mov address,offset arr
call	writeArry
push n
push 0
push address
call quickSort
add	esp,12
call writeArry
exit
main ENDP
END main